package summary;

/**
 * @Author: 海琳琦
 * @Date: 2021/12/16 12:55
 */
public class Title29 {

    /**                         up
     * 左闭右闭           left      right
     * @param matrix          down
     * @return
     */
    public static int[] spiralOrder(int[][] matrix) {
        int row = matrix.length;
        if (row == 0) {
            return new int[]{};
        }
        int column = matrix[0].length;
        int n = row * column;
        int[] result = new int[n];
        int left = 0, right = column - 1;
        int up = 0, down = row - 1;
        int count = 0;
        while (count < n) {
            //从左-》右
            for (int j = left; j <= right && count < n; j++) {
                result[count++] = matrix[up][j];
            }
            up++;
            //从上到下
            for (int i = up; i <= down && count < n; i++) {
                result[count++] = matrix[i][right];
            }
            right--;
            //从右到左
            for (int j = right; j >= left && count < n; j--) {
                result[count++] = matrix[down][j];
            }
            down--;
            //从下到上
            for (int i = down; i >= up && count < n; i--) {
                result[count++] = matrix[i][left];
            }
            left++;
        }
        return result;
    }

    public static void main(String[] args) {
//        int[][] matrix = {{1,2,3,4},{5,6,7,8},{9,10,11,12}};
        int[][] matrix = {{1,2,3},{4,5,6},{7,8,9}};
        spiralOrder(matrix);
    }
}
